package com.wzq.design.business.system.fun.service;

import com.wzq.design.base.dto.QueryByIdRequest;
import com.wzq.design.base.service.CommService;
import com.wzq.design.business.system.fun.dto.FunRequest;
import com.wzq.design.business.system.fun.dto.SysFunDto;
import com.wzq.design.business.system.fun.entity.SysFun;
import com.wzq.design.business.system.fun.mapper.FunMapper;
import com.wzq.ssm.parent.util.EntityUtil;
import com.wzq.ssm.parent.util.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wangzhiqiang
 * @since 2023/5/8 15:05
 */
@Service
public class FunService extends CommService<FunMapper, SysFun> {

    private final FunMapper funMapper;


    public FunService(FunMapper funMapper) {
        this.funMapper = funMapper;
    }

    @Transactional
    public SysFunDto save(SysFunDto dto) {
        SysFun sysFun;
        if (StringUtils.isBlank(dto.getId())) {
            sysFun = EntityUtil.castDtoToModel(dto, SysFun.class);
            setParentIds(sysFun);
            funMapper.insert(sysFun);
        } else {
            sysFun = funMapper.selectById(dto.getId());
            String oldParentId = sysFun.getParentId();
            EntityUtil.copyDtoToBean(dto, sysFun);
            if (!Objects.equals(oldParentId, dto.getParentId())) {
                setParentIds(sysFun);
            }
            funMapper.updateById(sysFun);
        }

        return SysFunDto.fromDb(sysFun);
    }


    public List<SysFunDto> list(FunRequest funRequest) {
        List<SysFun> sysFunList = funMapper.list(funRequest);
        return sysFunList.stream().map(SysFunDto::fromDb).collect(Collectors.toList());
    }

    public List<SysFunDto> listTree(FunRequest funRequest) {
        List<SysFun> sysFunList = funMapper.list(funRequest);
        return TreeUtil.build(sysFunList.stream().map(SysFunDto::fromDb).collect(Collectors.toList()));
    }


    public SysFunDto findById(QueryByIdRequest userRequest) {
        SysFun sysFun = funMapper.selectById(userRequest.getId());
        return SysFunDto.fromDb(sysFun);
    }

}
